package cn.com.b2office.service.impl;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.com.b2office.dao.ArticleDao;
import cn.com.b2office.domain.Article;
import cn.com.b2office.domain.ArticleCategory;
import cn.com.b2office.service.ArticleService;

public class ArticleServiceImpl implements ArticleService {

	// 文章更新次数.数值太低导致更新频繁，严重影响查询缓存的效果
	private static final int ARTICLE_HITS_UPDATE_LIMT = 20;

	// 文章点击次数
	private Map<Integer, Integer> articleClickMap = Collections
			.synchronizedMap(new HashMap<Integer, Integer>());

	private ArticleDao articleDao = null;

	public void setArticleDao(ArticleDao articleDao) {
		this.articleDao = articleDao;
	}

	public List<Article> findArticle(int categoryId, int firstResult,
			int maxResults) {
		return articleDao.listArticle(categoryId, firstResult, maxResults);
	}

	public Article getArticle(int articleId) {
		return articleDao.getArticle(articleId);
	}

	public Article getNextArticle(int curArticleId) {
		List<Article> list = articleDao.getNextArticles(curArticleId, 1);
		if (list == null || list.isEmpty())
			return null;
		return list.get(0);
	}

	/**
	 * 缓存点击次数
	 */
	public void addArticleHits(int articleId, int hits) {
		Integer clicks = articleClickMap.get(articleId);
		if (clicks == null) {
			clicks = 0;
		}
		clicks++;
		if (clicks > ARTICLE_HITS_UPDATE_LIMT) {
			articleDao.addArticleHits(articleId, clicks);
			clicks = 0;
		}
		articleClickMap.put(articleId, clicks);
	}

	public List<ArticleCategory> findCategory(List<Integer> categoryIdList) {
		return articleDao.listAllCategory(categoryIdList);
	}

	public List<Article> findArticle(int categoryId) {
		return articleDao.listAllArticle(categoryId);
	}

}
